import { ref } from 'vue'
import { defineStore } from 'pinia' 
import { loginService } from '@/api/index'
import router from '../router' 
import { setItem, getItem, removeAllItem } from '@/utils/storage' 
import { getyewu_list } from "@/api/index"

export const useUserStore = defineStore('users', () => { 

    
    const userid = ref(getItem('pulikbid') || '')
    const userData = ref(getItem('pulikbuserInfo') || '')
    const yewuList = ref('')

    const getYewuList = () =>{
      getyewu_list().then(data=>{
        yewuList.value = data
      })
    }
   
 

    const login = async (userInfo) => { 
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        loginService({
          username,
          password
        }).then(data => {       
            setItem('pulikbid', data.id) 
            setItem('pulikbuserInfo', data) 
            userid.value = data.id 
            userData.value = data
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    } 
 
 
     const loginOut = async () => {    
       removeAllItem() 
       userid.value = ''
       router.push('/login') 
     }
 
      
  return { login, userid, loginOut,userData,getYewuList,yewuList }
})
